
import mockRouterMap from "../../mock/index.js"
// import { isMock } from "../../mock/config.js"
const isMock = true

function parseJson(req) {
    return new Promise((resolve) => {
        let body = ''
        let jsonStr = ''
        req.on('data', function (chunk) {
            body += chunk
        })
        req.on('end', function () {
            try {
                jsonStr = JSON.parse(body)
            } catch (err) {
                jsonStr = ''
            }
            resolve(jsonStr)
            return
        })
    })
}

/** @type {import('vite').Plugin} */
export default {
    name: 'mock-proxy-plugin',
    configureServer({ middlewares }) {
        if (!isMock) return
        Object.keys(mockRouterMap).forEach(path => {
            middlewares.use(path, async (req, res) => {
                // 设置响应头
                res.setHeader('Content-Type', 'application/json');

                const content = mockRouterMap[path]

                if (req.method === "POST") {
                    req.body = await parseJson(req)
                }

                if (content.default) {
                    res.end(JSON.stringify(await content.default(req, res)));
                }
                if (typeof content === "function") {
                    res.end(JSON.stringify(await content(req, res)));
                }
                if (typeof content === 'object' && !content.default) {
                    res.end(JSON.stringify(content));
                }
            });
        })
    },
}